import { $tooltips } from '@/sun-components/SunMsg.js'
import { getToken } from '@/utils/auth'
// import SparkMD5 from 'spark-md5'
import store from '@/store'
const defaultSettings = require('@/settings.js')
let port = ''
const dev = process.env.NODE_ENV === 'development' ? `${defaultSettings.developmentApi}` : ''
if (store.getters.publicRoute === 'user') {
  if (store.getters.identity === '1') {
    port = '/api/principal'
  }
  if (store.getters.identity === '2') {
    port = '/api/teacher'
  }
  if (store.getters.identity === '3') {
    port = '/api/expert'
  }
}
if (store.getters.publicRoute === 'admin') {
  port = '/api/admin'
}

const $uploadFile = (file, data, path) => {
  // const uploadaction = `${dev}${port}/files/according/to/key/${store.getters.acadyearterm ? store.getters.acadyearterm.current?.acad_year_term : ''}`
  const uploadaction = `${dev}${port}/files/according/to/key/${path}`
  /**
  const xhr = new XMLHttpRequest()
  const spark = new SparkMD5.ArrayBuffer() // md5的ArrayBuffer加密类
  const fileReader = new FileReader()// 文件读取类
  const chunkSize = 1024 * 1024 * 30 // 单个分片大小
  let md5 = ''// 文件的唯一标识
  const optionFile = file.file // 需要分片的文件
  let fileChunkedList = [] // 文件分片完成之后的数组
  // 文件开始分片，push到fileChunkedList数组中， 并用第一个分片去计算文件的md5
  for (let i = 0; i < optionFile.size; i = i + chunkSize) {
    const tmp = optionFile.slice(i, Math.min((i + chunkSize), optionFile.size))
    if (i === 0) {
      fileReader.readAsArrayBuffer(tmp)
    }
    fileChunkedList.push(tmp)
  }
  console.log('文件分片完成之后的数组', fileChunkedList)
  // 在文件读取完毕之后，开始计算文件md5，作为文件唯一标识
  fileReader.onload = async(e) => {
    spark.append(e.target.result)
    md5 = spark.end() + new Date().getTime()
    console.log('md5', md5)
    // 将fileChunkedList转成FormData对象，并加入上传时需要的数据
    fileChunkedList = fileChunkedList.map((item, index) => {
      const formData = new FormData()
      if (data) {
        // 额外加入外面传入的data数据
        Object.keys(data).forEach(key => {
          formData.append(key, data[key])
        })
        // 这些字段看后端需要哪些，就传哪些，也可以自己追加额外参数
        formData.append('identifier', md5)// 文件标识
        formData.append('currentChunkSize', item.size)// 当前分块大小
        formData.append('totalChunks', fileChunkedList.length)// 总块数
      }
      console.log('formDataformData', formData)
    })
  }
  */
  return new Promise(function(resolve, reject) {
    let stime = 0
    let sloaded = 0
    const formData = new FormData()
    formData.append('file', file.file)
    const keysValue = Object.keys(data)
    keysValue.forEach(k => {
      formData.append(k, data[k])
    })
    const xhr = new XMLHttpRequest()
    if (JSON.stringify(path).indexOf('/api/') === -1) {
      xhr.open('post', uploadaction, true)
    } else {
      xhr.open('post', path, true)
    }
    // xhr.open('post', api || uploadaction, true)
    xhr.setRequestHeader('Authorization', getToken())
    xhr.onerror = (error) => {
      reject(error)
    }
    xhr.ontimeout = function timeout() {
      $tooltips('上传超时，请刷新重试...', 'warning')
    }
    xhr.upload.onloadstart = function() {
      stime = new Date().getTime()
      sloaded = 0
      file['uploadSpeed'] = '0 B/s'
      file.percentage = 0
      file['fileXhr'] = xhr
    }
    /**
     * 线上无法获取进度原因
     * 和mockjs有关，把项目中mockjs的引用去掉及注释main.js34行到37行
     */
    xhr.upload.onprogress = (evt) => {
      if (evt.lengthComputable) {
        file.percentage = Math.round(evt.loaded / evt.total * 100)
      }
      // 上传速度处理
      // 时间差
      const dTime = (new Date().getTime() - stime) / 1000
      console.log('时间差', dTime + 's')
      // 当前时间内上传的文件大小
      const dloaded = evt.loaded - sloaded // 整个文件上传完成的大小evt.loaded 上一次计算的大小sloaded
      console.log('字节差', dloaded)
      // 上传速率
      let unit = 'B/s'
      let speed = dloaded / dTime
      if (speed / 1024 / 1024 > 1) {
        unit = 'MB/s'
        speed = speed / 1024 / 1024
      } else if (speed / 1024 > 1) {
        unit = 'KB/s'
        speed = speed / 1024
      }
      file['uploadSpeed'] = `${speed.toFixed(2)} ${unit}`
      console.log('上传速度============', speed.toFixed(2) + unit)
      stime = new Date().getTime()
      sloaded = evt.loaded
    }
    xhr.send(formData)
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 422) {
          reject({ 'msg': '必须是文件!' })
        }
        if (xhr.status === 404) {
          reject({ 'msg': '上传到服务器失败!' })
        }
      }
      if (xhr.readyState === 4 && (xhr.status === 201 || xhr.status === 200)) {
        const response = JSON.parse(xhr.response)
        if (response.code === 1001) {
          reject({ 'msg': response.msg })
        }
        resolve(response)
      }
    }
  })
}
export default $uploadFile
